<template>
    <div class='approval'>
      <el-card class="box-card" style="margin-top: 110px;">
        <div class='title'>
          {{$t('achievements.title1')}}
        </div>
        <div class='menu-search'> 
            <div class='menu-title'>
                <!-- 业务ID -->
                <div class='searchItem'>
                    <span>{{$t('achievements.orderId')}}</span>
                    <el-input v-model='listQuery.orderId' :placeholder="$t('rule.orderId')" size='small'></el-input>
                </div>
                <!-- 客户姓名 -->
                <div class='searchItem'>
                    <span>{{$t('achievements.realName')}}</span>
                    <el-input v-model='listQuery.realName' :placeholder="$t('rule.realName')" size='small'></el-input>
                </div>
                <!-- 手机号 -->
                <div class='searchItem'>
                    <span>{{$t('achievements.phoneNo')}}</span>
                    <el-input v-model='listQuery.mobile' :placeholder="$t('rule.phoneNo')" size='small'></el-input>
                </div>
                <!-- 订单状态 -->
                <div class='searchItem'>
                    <span>{{$t('orderQuery.orderStatus')}}</span>
                    <el-select v-model='listQuery.status' size='small'>
                          <el-option
                          v-for='item in orderStatus'
                          :key='item.value'
                          :label='item.label'
                          :value='item.value'>
                          </el-option>
                      </el-select>
                </div>
                <!-- 申请时间 -->
                <div class='searchItem searchItem-date'>
                    <span>{{$t('achievements.crtTime')}}</span>
                    <el-date-picker
                    size='small'
                    v-model="listQuery.applicationTimeStart"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :placeholder="$t('rule.beginDate')">
                    </el-date-picker>
                    <b>{{$t('approval.go')}}</b>
                    <el-date-picker
                    size='small'
                      v-model="listQuery.applicationTimeEnd"
                      type="date"
                      value-format="yyyy-MM-dd"
                      :placeholder="$t('rule.endDate')">
                    </el-date-picker>
                </div>
            </div>
            <div class='menu-title-btn'>
                <button type='button' @click='search'>
                    {{$t('btn.query')}}
                </button>
                <button type='button' @click='reset'>
                    {{$t('btn.reset')}}
                </button>
                <button type='button' @click="handleDownload" :disabled="expDis" v-if="orderBalance_btn_export">
                    {{$t('btn.export')}}
                </button>
                <!-- 展期 -->
                <button type='button' @click='extension'>
                    {{$t('paymentHistory.rollover')}}
                </button>
                <!-- 结清 -->
                <button type='button' @click='settle'>
                    {{$t('paymentHistory.settle')}}
                </button>
            </div>
        </div>
      </el-card>
      <el-card class='box-card' style="margin-top: 10px;margin-bottom: 20px;">
        <div class='title'>
            {{$t('achievements.title2')}}
        </div>
        <el-table
            v-loading="listLoading"
            ref='multipleTable'
            :data='tableData'
            tooltip-effect='dark'
            style='width: 100%'
            @selection-change='handleSelectionChange'
            border
            stripe
            size='mini'>
            <el-table-column
            header-align='center'
            align='center'
            type='selection'
            width='55'>
            </el-table-column>
            <!-- 业务ID -->
            <el-table-column align="center" header-align="center" 
            :label="$t('achievements.orderId')"
            width='200'>
            <template slot-scope="scope">
                <span>{{scope.row.orderId}}</span>
            </template>
            </el-table-column>
            <!-- 客户姓名 -->
            <el-table-column
            prop='realName' align="center" header-align="center" 
            :label="$t('achievements.realName')"
            width='180'>
            </el-table-column>
            <!-- 手机号 -->
            <el-table-column
            prop='mobile' align="center" header-align="center" 
            :label="$t('achievements.phoneNo')"
            width='180'>
            </el-table-column>
            <!-- 审批额度 -->
            <el-table-column 
            prop='approvedAmt' align="center" header-align="center" 
            :label="$t('orderQuery.approvalAmt')"
            width='150'>
            </el-table-column>
            <!-- 审批人 -->
            <el-table-column align="center" header-align="center" 
            prop='businessUserName'
            :label="$t('achievements.loanUser')"
            width='150'>
            </el-table-column>
            <!-- 申请时间 -->
            <el-table-column align="center" header-align="center" 
            prop="applicationTime"
            :label="$t('achievements.crtTime')"
            width='150'>
            </el-table-column>
            <!-- 放款时间 -->
            <el-table-column 
            prop="lendDate" align="center" header-align="center" 
            :label="$t('orderQuery.loanTime')"
            width='150'>
            </el-table-column>
            <!-- 应还金额 -->
            <el-table-column
            prop='repayAmt' align="center" header-align="center" 
            :label="$t('collDetail.shouldAmt')"
            width='150'>
            </el-table-column>
            <!-- 订单状态 -->
            <el-table-column
            prop='status' align="center" header-align="center" 
            :label="$t('orderQuery.orderStatus')"
            width='110'>
            <template slot-scope="scope">
              <span v-if="scope.row.status=== 3">{{$t('processing.normal')}}</span>
              <span v-if="scope.row.status=== 6">{{$t('collDetail.overdue')}}</span>
              <span v-if="scope.row.status=== 7">{{$t('paymentHistory.rollover')}}</span>
          </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="listQuery.page"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="listQuery.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
          </el-pagination>
        </div>
      </el-card>
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogRolloverVisible" :before-close = "closeDialog">
        <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px">
          <!-- 应还金额 -->
          <el-form-item :label="$t('collDetail.shouldAmt')">
            <el-input v-model="form.amountDue" auto-complete="off" :disabled="true" size="small"></el-input>
          </el-form-item>
          <!-- 实收金额 -->
          <el-form-item :label="$t('paymentHistory.amount')" prop="paidAmount">
            <el-input v-model="form.paidAmount" auto-complete="off" size="small"></el-input>
          </el-form-item>
          <!-- 原因 -->
          <el-form-item :label="$t('paymentHistory.reason')" prop="reason">
            <el-input type="textarea" v-model="form.reason" auto-complete="off" size="medium" :placeholder="$t('rule.toLength')" :maxlength="500"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">{{$t('btn.cancel')}}</el-button>
          <el-button v-if="dialogStatus === 'rollover'" type="primary" @click="rolloverFn('ruleForm')">{{$t('btn.confirm')}}</el-button>
          <el-button v-else type="primary" @click="settleFn('ruleForm')">{{$t('btn.confirm')}}</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
import { mapGetters } from "vuex";
import { dataMasking } from 'utils/index';
import { page, extensionAmount, flatAccount, pageExport } from 'api/trust/orderBalance/index'
export default {
  name: "orderBalance",
  data() {
    return {
      orderBalance_btn_export: false,
      textMap: {
        rollover: this.$t('paymentHistory.rollover'),
        settle: this.$t('paymentHistory.settle')
      },
      dialogStatus: '',
      form: {
        orderId: '',
        amountDue: '',
        paidAmount: '',
        reason: '',
        flatAccountType: '',
      },
      dialogRolloverVisible: false,
      textarea: '',
      expDis: true,
      listLoading: false,
      total: null,
      listQuery: {
        limit: 5,
        page: 1,
        orderId: '', // 业务ID
        realName: '',
        mobile: '',
        status: '', // 订单状态
        applicationTimeStart: '', // 申请时间
        applicationTimeEnd: ''
      },
      tableData: [],
      multipleSelection: [],
      orderStatus: [
        {
          value: 3,
          label: this.$t('processing.normal')
        },
        {
          value: 6,
          label: this.$t('collDetail.overdue')
        },
        {
          value: 7,
          label: this.$t('paymentHistory.rollover')
        }
      ],
      rules: {
        paidAmount: [
          { required: true, message: this.$t('paymentHistory.rule1'), trigger: 'blur' }
        ],
        reason: [
          { required: true, message: this.$t('paymentHistory.rule2'), trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    if (this.orderBalancePage.has(this.$route.path)) {
      this.listQuery = this.orderBalancePage.get(this.$route.path)
    }
    this.getList();
    this.orderBalance_btn_export = this.elements['orderBalance:btn_export'];
  },
  computed: {
    ...mapGetters(["elements", "orderBalancePage"])
  },
  methods: {
    closeDialog(done) {
      done();
      this.$refs["ruleForm"].resetFields();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogRolloverVisible = false;
    },
    //展期确认
    rolloverFn(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogStatus = 'rollover') {
            this.form.flatAccountType = 2
          }
          this.form.orderId = this.multipleSelection[0].orderId
          let msg = this.form.amountDue.replace(/,/g,'');
          this.form.amountDue = Number(msg)
          flatAccount(this.form)
          .then(res => {
            if (res.status === 200) {
              this.getList();
              this.$message({
                showClose: true,
                message: this.$t('approvalDetail.status5'),
                type: 'success'
              });
              this.$refs[formName].resetFields();
            }
          })
          this.dialogRolloverVisible = false
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //结清确认
    settleFn(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogStatus = 'settle') {
            this.form.flatAccountType = 1
          }
          this.form.orderId = this.multipleSelection[0].orderId
          let msg = this.form.amountDue.replace(/,/g,'');
          this.form.amountDue = Number(msg)
          flatAccount(this.form)
          .then(res => {
            if (res.status === 200) {
              this.getList();
              this.$message({
                showClose: true,
                message: this.$t('approvalDetail.status3'),
                type: 'success'
              });
              this.$refs[formName].resetFields();
            }
          })
          this.dialogRolloverVisible = false
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    extension() {
      if (this.multipleSelection.length === 1){
        this.dialogStatus = 'rollover';
        extensionAmount(this.multipleSelection[0].orderId)
        .then(res => {
          let re = /(?=(?!\b)(\d{3})+$)/g;
          let str = String(res.data.amountDue)
          res.data.amountDue =  str.replace(re, ',');
          this.form.amountDue = res.data.amountDue
        })
        this.dialogRolloverVisible = true
      } else if (this.multipleSelection.length <= 0){
        this.$message({
          showClose: true,
          message: this.$t('approval.msg1'),
          type: 'warning'
        });
      } else if (this.multipleSelection.length > 1) {
        this.$message({
          showClose: true,
          message: this.$t('approval.msg2'),
          type: 'warning'
        });
      }
    },
    settle() {
      if (this.multipleSelection.length === 1){  
        this.dialogStatus = 'settle';
        let re = /(?=(?!\b)(\d{3})+$)/g;
        let str = String(this.multipleSelection[0].repayAmt)
        this.multipleSelection[0].repayAmt =  str.replace(re, ',');
        this.form.amountDue = this.multipleSelection[0].repayAmt;
        this.dialogRolloverVisible = true;
      } else if (this.multipleSelection.length <= 0){
        this.$message({
          showClose: true,
          message: this.$t('approval.msg1'),
          type: 'warning'
        });
      } else if (this.multipleSelection.length > 1) {
        this.$message({
          showClose: true,
          message: this.$t('approval.msg2'),
          type: 'warning'
        });
      }
    },
    // 点击导出
    handleDownload() {
      this.listLoading = true;
      pageExport(this.listQuery)
      .then(response => {
        response.forEach(item => {
          if (item.realName || item.mobile) {
            item.realName = dataMasking(item.realName)
            item.mobile = dataMasking(item.mobile)
          }
          // 订单状态
          switch (item.status) {
            case 3:
              item.status = this.$t('processing.normal')
              break;
            case 6:
              item.status = this.$t('collDetail.overdue')
              break;
            case 7:
              item.status = this.$t('paymentHistory.rollover')
              break;
          }
        })
        require.ensure([], () => {
          const { export_json_to_excel } = require('@/vendor/Export2Excel')
          const tHeader = [ this.$t('achievements.orderId'), this.$t('achievements.realName'), this.$t('achievements.phoneNo'), this.$t('orderQuery.approvalAmt'), this.$t('achievements.loanUser'), this.$t('achievements.crtTime'), this.$t('orderQuery.loanTime'), this.$t('collDetail.shouldAmt'), this.$t('orderQuery.orderStatus')];
          const filterVal = [ 'orderId', 'realName', 'mobile', 'approvedAmt', 'businessUserName', 'applicationTime', 'lendDate', 'repayAmt', 'status'];
          const list = response;
          const data = this.formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, this.$t('route.orderBalance'))
          this.listLoading = false;
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // if (j === 'realName' || j === 'mobile') {
        //   return dataMasking(v[j])
        // }
        return v[j]
      }))
    },
    getList() {
      this.listLoading = true;
      this.$store.dispatch('saveOrderBanlancePage', { path: this.$route.path, listQuery: this.listQuery });
      page(this.listQuery)
        .then(response => {
          response.records.forEach(item => {
            let re = /(?=(?!\b)(\d{3})+$)/g;
            let str = String(item.approvedAmt)
            item.approvedAmt =  str.replace(re, ',');
            let str2 = String(item.repayAmt)
            item.repayAmt =  str2.replace(re, ',');
          })
          this.expDis = false;
          this.listLoading = false;
          this.tableData = response.records;
          this.total = Number(response.total);
        })
    },
    // 查询
    search() {
      this.listQuery.page = 1;
      this.getList();
    },
    // 重置
    reset() {
      this.listQuery.limit = 5;
      this.listQuery.page = 1;
      this.listQuery.orderId = "";
      this.listQuery.realName = "";
      this.listQuery.mobile = "";
      this.listQuery.status = "";
      this.listQuery.applicationTimeStart = "";
      this.listQuery.applicationTimeEnd = "";
    },
    // 选中的数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList()
    }
  }
};
</script>

<style scoped lang='scss'>
.box-card {
  width: 95%;
  margin-left: 2.5%;
  margin-right: 2.5%;
}
.title {
  line-height: 30px;
  font-size: 16px;
  display: flex;
  align-items: center;
  font-weight: bold;
}
.title:before{
  display: block;
  content: "";
  width: 3px;
  height: 16px;
  background-color: #309afe;
}
.title:before {
  margin-right: 8px;
}
::before {
  box-sizing: inherit;
  -webkit-tap-highlight-color: transparent;
}
.menu-title {
  width: 100%;
  box-sizing: border-box;
  background: #ffffff;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .searchItem {
    display: flex;
    align-items: center;
    padding: 10px  0;
    span {
      display: inline-block;
      width: 100px;
      text-align: right;
      font-size: 12px;
      color: #5f5f61;
      padding-right: 5px;
    }
    div:nth-child(2) {
      width: 150px;
    }
  }
  .searchItem-date {
    display: flex;
    align-items: center;
    padding: 10px  0;
    b {
      margin: 0 10px;
      font-weight: normal;
      font-size: 12px;
      color: #5f5f61;
    }
    div {
       width: 150px;
    }
  }
}
.menu-title-btn {
  padding: 10px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
    &:nth-child(2) {
      background: #ebf5ff;
      color: #20a0ff;
      border: 1px solid #abd5ff;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.menu-list {
  padding: 20px 0;
  box-sizing: border-box;
  button {
    padding: 0 20px;
    height: 28px;
    background: #20a0ff;
    color: #fff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
    margin-left: 10px;
    &:nth-child(1) {
      margin-left: 0;
    }
  }
  button[disabled] {
    padding: 0 20px;
    height: 28px;
    background: #c1e0ff;
    color: #fafbff;
    outline: none;
    border-width: 0;
    border-radius: 4px;
    font-size: 12px;
  }
}
.href {
  cursor: pointer; 
  color: #20a0ff;
  border-bottom: 1px solid #20a0ff;
}
</style>